
class TreeNode{
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int val){
        this.val = val;
    }
}
public class Test {
    //从前序与中序遍历序列构造二叉树:
    // 给定两个整数数组 preorder 和 inorder ，其中 preorder 是二叉树的先序遍历，
    // inorder 是同一棵树的中序遍历，请构造二叉树并返回其根节点
    public static int preIndex = 0;
    public TreeNode buildTree1(int[] preorder, int[] inorder){
        return buildTreeChild1(preorder,inorder,0,preorder.length-1);
    }
    public TreeNode buildTreeChild1(int[] preorder, int[] inorder, int inBegin, int inEnd){
        //结束递归
        if (inBegin > inEnd){
            return null;
        }
        TreeNode root = new TreeNode(preorder[preIndex]);
        preIndex++;
        //得到root在inOder里面的索引下标
        int rootIndex = find(inorder,inBegin,inEnd,preorder[preIndex]);
        root.left = buildTreeChild1(preorder, inorder, inBegin, rootIndex - 1);
        root.right = buildTreeChild1(preorder, inorder, rootIndex + 1, inEnd);
        return root;
    }
    public int find(int[] inOder, int inBegin, int inEnd, int key){
        for (int i = inBegin;i <= inEnd;i++){
            if (inOder[i] == key){
                return i;
            }
        }
        return -1;
    }

    //从中序和后序遍历数列构造二叉树：
    // 给定两个整数数组 inorder 和 postorder ，其中 inorder 是二叉树的中序遍历，
    // postorder 是同一棵树的后序遍历，请你构造并返回这颗 二叉树 。
    public int postIndex = 0;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        postIndex = postorder.length - 1;
        return buildTreeChild(inorder,postorder,0,postorder.length - 1);
    }
    public TreeNode buildTreeChild(int[] inorder, int[] postorder, int inBegin, int inEnd){
        //结束递归
        if (inBegin > inEnd){
            return null;
        }
        TreeNode root = new TreeNode(postorder[postIndex]);
        //得到root在inOder里面的索引下标
        int rootIndex = find(inorder,inBegin,inEnd,postorder[preIndex]);
        postIndex--;
        root.right = buildTreeChild1(inorder, postorder, rootIndex + 1, inEnd);
        root.left = buildTreeChild1(inorder, postorder, inBegin, rootIndex - 1);
        return root;
    }
}
